const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const xmlParser = require('koa-xml-body')
// const session = require('koa-session')
const path = require('path')

const index = require('./routers')
const lottery = require('./routers/lottery')

app.keys = ['yezi', 'yezigd']

app.use(xmlParser())
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())

app.use(views(path.join(__dirname, 'dist'), {
  map: {
    html: 'underscore'
  },
  maxage: 365 * 24 * 60 * 60
}))

app.use(require('koa-static')(path.join(__dirname, 'dist')))

app.use(index.routes(), index.allowedMethods())
app.use(lottery.routes(), lottery.allowedMethods())

// logger
app.use(async (ctx, next) => {
  const start = Date.now()
  await next()
  const ms = Date.now() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}`)
})

// production error handler
// no stacktraces leaked to user
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    ctx.status(err.status || 500)
    ctx.body = {
      code: err.status || 500, message: err.message
    }
  }
})

app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
